function [bar_pos,bar_neg,x_pos,x_neg]=barstacked(in)

% The function [bar_pos,bar_neg,x_pos,x_neg]=barstackedaux(in) decomposes
% matric <in> into matrix <bar_pos> containing non-negative entries and
% zeroes otherwise and matrix <bar_neg> containing all negative entries and
% zeroes otherwise.
% <x_pos> and <x_neg> are matrices needed to plot errorbars (whiskers).
% <x_pos> is the matrix containing the cumulative sum of the non-negative
% entries in <in> but NaN otherwise; <x_neg> is the analogue but for
% negative entries.
% 
% Written by Matthias Kehrig, 16 July 2018.

aux=(in>=0);
bar_pos=aux.*in;
bar_neg=(1-aux).*in;

if nargout>2
    [T,K]=size(aux);
    x_pos=cumsum(bar_pos')';
    x_neg=cumsum(bar_neg')';
    x_pos=reshape(x_pos,T*K,1);
    x_neg=reshape(x_neg,T*K,1);
    aux=reshape(aux,T*K,1);
    for i=1:T*K
        if aux(i)==0
            x_pos(i)=nan;
        elseif aux(i)==1
            x_neg(i)=nan;
        end
    end
    x_pos=reshape(x_pos,T,K);
    x_neg=reshape(x_neg,T,K);
end
